package com.hnust.wswx.moblieStuBack.controller;


import com.hnust.wswx.moblieStuBack.service.LoginService;
import com.hnust.wswx.moblieStuBack.util.JwtToken;
import com.hnust.wswx.moblieStuBack.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 学生登录
     * 学生输入账号密码
     * 后端验证账号密码是否正确
     * 如果正确 返回状态码200和token
     * 如果账号密码错误 返回状态码401 和提示“账号或密码错误”
     * 其他服务器发生错误情况返回500
     */
    @PostMapping("/student")
    public Result<Object> studentLogin(@RequestBody Map<String,Object> map){
        try {
            String account = map.get("account").toString();
            String password = map.get("password").toString();
            if(loginService.StudentLogin(account,password)){
                String token = JwtToken.createToken(account,password);
                Map<String,String> Token = new HashMap<>();
                Token.put("token",token);
                return new Result<Object>(200,"登录成功",Token);
            }
            else{
                return new Result<Object>(401,"账号密码错误",null);
            }
        } catch (Exception e) {
            return new Result<Object>(500,e.getMessage().toString(),null);
        }
    }
}
